/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server.domain;

import Server.domain.items.Equipment;
import Server.domain.items.Weapon;
import Server.domain.items.ItemAttribute;
import Server.domain.items.Belt;
import Server.domain.items.LegArmor;
import Server.domain.items.Necklace;
import Server.domain.items.Gloves;
import Server.domain.items.Ring;
import Server.domain.items.ChestArmor;
import Server.domain.items.Helmet;
import Server.domain.items.ItemAttributeType;
import Server.domain.items.MeleeWeapon;
import Server.domain.items.RangedWeapon;
import Server.domain.items.Boots;
import Server.domain.items.Item;
import Client.gui.TextEncoder;
import Server.persistentie.UserFactory;
import Server.gui.ServerWindow;
import Server.network.NetworkMainServer;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Ripper
 */
public class ServerDomainController 
{
    private ServerWindow serverWindow;
    private List<User> users;
    
    private NetworkMainServer nms;
    private Thread networkThread;
    
    private List<GameSession> inactiveSessions;
    private List<GameSession> activeSessions;
    private List<Thread> activeSessionThreads;
    
    private UserFactory userfact;
    
    public ServerDomainController(ServerWindow sw) throws Exception
    {
        inactiveSessions = new ArrayList<GameSession>();
        activeSessions = new ArrayList<GameSession>();
        activeSessionThreads = new ArrayList<Thread>();
        
        userfact = new UserFactory();
        users = userfact.getUsers();
        nms = new NetworkMainServer(this, 4441);
        networkThread = new Thread(nms);
        networkThread.start();
        
        setServerWindow(sw);
    }
    
    public ServerDomainController(ServerWindow sw, List<User> users) throws Exception
    {
        inactiveSessions = new ArrayList<GameSession>();
        activeSessions = new ArrayList<GameSession>();
        activeSessionThreads = new ArrayList<Thread>();
        
        userfact = new UserFactory();
        setUsers(users);
        nms = new NetworkMainServer(this, 4441);
        networkThread = new Thread(nms);
        networkThread.start();
        
        setServerWindow(sw);
    }

    public List<User> getUsers() { return users; }
    public final void setUsers(List<User> users) { this.users = users; }
    
    public void logMessageToScreen(String message)
    {
        serverWindow.logMessage(message);
    }
    public String register(String[] data)
    {
        String firstName = data[0];
        String lastName = data[1];
        String username = data[2];
        String password = data[3];
        String email = data[4];
        
        for(User u: users)
        {
            if(u.getUsername().toLowerCase().equals(username.toLowerCase()))
            {
                return "USERNAME_TAKEN#";
            }
            else if(u.getEmail().toLowerCase().equals(email.toLowerCase()))
            {
                return "EMAIL_TAKEN#";
            }
        }
        
        User u = new User(username, password, firstName, lastName, email);
        u.setLoggedIn(true);
        users.add(u);
        logMessageToScreen("New user has registered: "+u.getUsername()+".");
        
        logMessageToScreen("New user registered: "+username+"(email="+email+")");
        
        return "REGISTER_OK:"+username;
    }
    public String login(String user, String pass)
    {
        System.out.println("user trying to login: "+user+" with password "+pass);
        for(User u: users)
        {
            if(u.getUsername().toLowerCase().equals(user.toLowerCase()))
            {
                if(!u.isLoggedIn())
                {
                    //check pw
                    if(u.getPassword().equals(pass))
                    {
                        logMessageToScreen("User "+u.getUsername()+" has logged in.");
                        u.setLoggedIn(true);
                        return "LOGIN_OK:"+user;
                    }
                    else
                    {
                        return "WRONG_PASSWORD#";
                    }
                }
                else
                {
                    return "ALREADY_LOGGED_IN#";
                }
            }
        }
        return "UNKOWN_USER#";
    }
    public void logout(String username)
    {
        for(User u: users)
        {
            if(u.getUsername().toLowerCase().equals(username.toLowerCase()))
            {
                if(u.isLoggedIn())
                {
                    logMessageToScreen("User "+username+" is now logged out.");
                    u.setLoggedIn(false);
                }
            }
        }
    }

    public ServerWindow getServerWindow() { return serverWindow; }
    public final void setServerWindow(ServerWindow serverWindow) { this.serverWindow = serverWindow; }
    
    public User getUser(String username)
    {
        for(User u: users)
        {
            if(u.getUsername().toLowerCase().equals(username.toLowerCase()))
            {
                return u;
            }
        }
        return null;
    }
    public void processMessageFromServerAdmin(String msg)
    {
        if(msg.equals("?") || msg.equals("help"))
        {
            logMessageToScreen("------------------------");
            logMessageToScreen("Available commands:");
            logMessageToScreen("------------------------");
            logMessageToScreen("");
            logMessageToScreen("? or help: display this message.");
            logMessageToScreen("addxp:playername:amount or givexp:playername:amount give a player some experience");
            logMessageToScreen("speak:sessionname:text");
            logMessageToScreen("");
            logMessageToScreen("-------------------");
        }
        else if(msg.startsWith("addxp:") || msg.startsWith("givexp:"))
        {
            try
            {
                String[] parts = msg.split(":");
                String player = parts[1];
                String amount = parts[2];
                int amountInt = Integer.parseInt(amount);
                
                boolean plrfound = false;
                for(User u: users)
                {
                    for(Player p: u.getPlayers())
                    {
                        if(p.getPlayerName().toLowerCase().equals(player.toLowerCase()))
                        {
                            plrfound = true;
                            p.addExperience(amountInt);
                            logMessageToScreen("player "+p.getPlayerName()+" was given "+amount+" experience.");
                        }
                    }
                }
                
                if(!plrfound)
                {
                    logMessageToScreen("No such player found.");
                }
                
            }
            catch(Exception ex)
            {
                logMessageToScreen("unable to donate experience:");
                logMessageToScreen(ex.toString());
            }
        }
        else if(msg.startsWith("speak:"))
        {
            try
            {
                GameSession gs = null;
                for(GameSession gss: activeSessions)
                {
                    if(gss.getSessionName().toLowerCase().equals(msg.split(":")[1].toLowerCase()))
                    {
                        gs = gss;
                    }
                }
                
                if(gs == null)
                {
                    throw new Exception("Active session "+msg.split(":")[1]+" not found!");
                }
                
                String decoded = msg.split(":")[2];
                String encoded = TextEncoder.encodeText(decoded);
                
                gs.playerSays("Admin", encoded);
            }
            catch(Exception ex)
            {
                logMessageToScreen("unable to speak to session: "+ex.getMessage());
            }
        }
        else
        {
            logMessageToScreen("Message received. However, this functionality is still under construction.");
            
        }
    }
    public String processRequest(String source, String request)
    {
        //temp
        //logMessageToScreen("Message from "+source+": "+request);
        
        User u = getUser(source);
        
        if(u == null)
        {
            return "";
        }
        
        String[] requests = request.split(";");
        
        String[] answers = new String[requests.length];
        for(int a = 0; a < requests.length; a++)
        {
            try
            {
                answers[a] = individualRequest(u, requests[a]);
            }
            catch(NullPointerException npe)
            {
                answers[a] = "";
            }
        }
        
        String response = "";
        for(String s: answers)
        {
            response += s + ";";
        }
        return response;
    }
    public String individualRequest(User source, String request)
    {
        if(request.equals("user_gold?"))
        {
            return source.getGold()+"";
        }
        else if(request.equals("actvplr_name?"))
        {
            return source.getSelectedPlayer().getPlayerName();
        }
        else if(request.equals("actvplr_xp2lvl?"))
        {
            return source.getSelectedPlayer().getExpPercentage()+"";
        }
        else if(request.equals("actvplr_lvl?"))
        {
            return source.getSelectedPlayer().getLevel()+"";
        }
        else if(request.equals("actvplr_physdmg?"))
        {
            return source.getSelectedPlayer().getPhysicalDamage()+"";
        }
        else if(request.equals("activeplr_magdmg?"))
        {
            return source.getSelectedPlayer().getMagicDamage()+"";
        }
        else if(request.equals("activeplr_physarm?"))
        {
            return source.getSelectedPlayer().getArmor()+"";
        }
        else if(request.equals("activeplr_magarm?"))
        {
            return source.getSelectedPlayer().getMagicArmor()+"";
        }
        else if(request.equals("activeplr_aggrompr?"))
        {
            return source.getSelectedPlayer().getAggroMultiplier()+"";
        }
        else if(request.equals("activeplr_maxhp?"))
        {
            return source.getSelectedPlayer().getMaxHitpoints()+"";
        }
        else if(request.equals("activeplr_maxmana?"))
        {
            return source.getSelectedPlayer().getMaxManapoints()+"";
        }
        else if(request.equals("activeplr_maxstam?"))
        {
            return source.getSelectedPlayer().getMaxStaminapoints()+"";
        }
        else if(request.equals("activeplr_hpreg?"))
        {
            return source.getSelectedPlayer().getHitpointRegen()+"";
        }
        else if(request.equals("activeplr_mpreg?"))
        {
            return source.getSelectedPlayer().getManapointRegen()+"";
        }
        else if(request.equals("activeplr_spreg?"))
        {
            return source.getSelectedPlayer().getStamanapointRegen()+"";
        }
        else if(request.equals("activeplr_critchance?"))
        {
            return source.getSelectedPlayer().getCriticalChance()+"";
        }
        else if(request.equals("activeplr_critdmgmpr?"))
        {
            return source.getSelectedPlayer().getCriticalMultiplier()+"";
        }
        else if(request.equals("activeplr_atkspd?"))
        {
            return source.getSelectedPlayer().getAttackSpeed()+"";
        }
        else if(request.equals("activeplr_movspd?"))
        {
            return source.getSelectedPlayer().getWalkingSpeed()+"";
        }
        else if(request.equals("activeplr_prctspvp?"))
        {
            return source.getSelectedPlayer().getSpellvampPercentage()+"";
        }
        else if(request.equals("activeplr_prctlifesteal?"))
        {
            return source.getSelectedPlayer().getLifestealPercentage()+"";
        }
        else if(request.equals("select_next_player"))
        {
            source.selectNextActivePlayer();
            return "done";
        }
        else if(request.equals("select_prev_player"))
        {
            source.selectPreviousActivePlayer();
            return "done";
        }
        else if(request.startsWith("create_new_player"))
        {
            String[] data = request.split(":");
            Player player = new Player(data[1]); 
            List<ItemAttribute> attributes = new ArrayList<ItemAttribute>();
            MeleeWeapon mw = new MeleeWeapon("dagger", 10, 100001, 15, 2, 0, 45, 45, false, attributes);
            player.equip(mw);
            
            source.addPlayer(player);
            
            source.setSelectedPlayerIndex(source.getPlayers().size()-1);
            
            //TEMPORARILY (to test) -------------------------------------------------------------
            List<ItemAttribute> attributes3 = new ArrayList<ItemAttribute>();
            attributes3.add(new ItemAttribute(ItemAttributeType.MAXHP, 69));
            LegArmor la = new LegArmor("sexypants", 20, 100003, 24, 34, attributes3);
            player.addItem(la);

            List<ItemAttribute> attributes4 = new ArrayList<ItemAttribute>();
            attributes4.add(new ItemAttribute(ItemAttributeType.MAXHP, 666));
            LegArmor la2 = new LegArmor("sexualpants", 20, 100004, 24, 35, attributes4);
            player.addItem(la2);

            List<ItemAttribute> attributes5 = new ArrayList<ItemAttribute>();
            attributes5.add(new ItemAttribute(ItemAttributeType.CRITCHANCE, 0.05));
            Gloves gl = new Gloves("sharp fingernails", 20, 100005, 24, 35, attributes5);
            player.addItem(gl);
            Item i = new Item("unwearable helmet", 10, 100000);
            player.addItem(i);
            
            Gloves gl2 = new Gloves("oven mits", 20, 100006, 2, 75, new ArrayList<ItemAttribute>());
            player.addItem(gl2);
            
            Ring r1 = new Ring("sapphire ring", 1000, 100007, 1, 1, new ArrayList<ItemAttribute>());
            Ring r2 = new Ring("ruby ring", 1000, 100008, 1, 1, new ArrayList<ItemAttribute>());
            Ring r3 = new Ring("emerald ring", 1000, 100009, 1, 1, new ArrayList<ItemAttribute>());
            Ring r4 = new Ring("amethyst ring", 1000, 100010, 1, 1, new ArrayList<ItemAttribute>());
            r1.addEquipmentAttribute(new ItemAttribute(ItemAttributeType.MPREGEN, 0.1));
            r2.addEquipmentAttribute(new ItemAttribute(ItemAttributeType.HPREGEN, 0.1));
            r3.addEquipmentAttribute(new ItemAttribute(ItemAttributeType.SPREGEN, 0.1));
            r4.addEquipmentAttribute(new ItemAttribute(ItemAttributeType.MAXHP, 25));
            r4.addEquipmentAttribute(new ItemAttribute(ItemAttributeType.MAXSP, 25));
            r4.addEquipmentAttribute(new ItemAttribute(ItemAttributeType.MAXMP, 25));
            player.addItem(r1);
            player.addItem(r2);
            player.addItem(r3);
            player.addItem(r4);
            
            Boots b1 = new Boots("red slippers", 10, 100011, 2, 5, new ArrayList<ItemAttribute>());
            player.addItem(b1);
            List<ItemAttribute> att6 = new ArrayList<ItemAttribute>();
            att6.add(new ItemAttribute(ItemAttributeType.MAXHP, 100));
            att6.add(new ItemAttribute(ItemAttributeType.MOVEMENT, 500));
            att6.add(new ItemAttribute(ItemAttributeType.LIFESTEAL, 0.1));
            player.addItem(new Boots("boots of poon", 1000, 100012, 50,50, att6));
            player.addItem(new Boots("steel boots", 25, 100013, 25, 5, new ArrayList<ItemAttribute>()));
            player.addItem(new ChestArmor("golden armor", 10000, 100014, 50, 20, new ArrayList<ItemAttribute>()));
            player.addItem(new ChestArmor("silver armor", 5000, 100018, 35, 10, new ArrayList<ItemAttribute>()));
            player.addItem(new ChestArmor("leather armor", 100, 100015, 20, 5, new ArrayList<ItemAttribute>()));;
            player.addItem(new Helmet("sapphire crown", 7500, 100016, 20, 5, new ArrayList<ItemAttribute>()));
            player.addItem(new Necklace("tooth chain necklace", 200, 100017, 2, 3, new ArrayList<ItemAttribute>()));
            player.addItem(new RangedWeapon("simple bow", 100, 100019, 50, 0, 0, 100, true, new ArrayList<ItemAttribute>()));
            //TEMPORARILY (to test) -------------------------------------------------------------
            
            return "done";
        }
        else if(request.equals("actvplr_attributeinfo?"))
        {
            //"benefit:","point spent:","current bonus:","max:"
            //x,x,x-x,x,x-x,x,x
            
            String data = "";
            
            LevelupAttributeManager lam = source.getSelectedPlayer().getLevelupAttributeManager();
            for(int a = 0; a < lam.getAttributeCount();a++)
            {
                data += lam.getAttributeSingleValue(a) + ","+ 
                        lam.getPointsSpentIn(a) +","+
                        lam.getAttributeValue(a) + "," + 
                        lam.getMaximumPointsSpentIn(a) + "," +
                        lam.getAttributeDescription(a);
                
                if(a < lam.getAttributeCount() - 1)
                {
                    data += "-";
                }
            }
            
            return data;
        }
        else if(request.equals("actvplr_attributepointsavailable?"))
        {
            return ""+source.getSelectedPlayer().getLevelupAttributeManager().attributePointsAvailable(source.getSelectedPlayer().getLevel());
        }
        else if(request.startsWith("actvplr_levelup_attribute:"))
        {
            String[] data = request.split(":");
            int index = Integer.parseInt(data[1]);
            
            if(source.getSelectedPlayer().spendLevelUpAttributePoint(index))
            {
                return "done";
            }
            else
            {
                return "insufficient";
            }
        }
        else if(request.equals("actvplr_colors?"))
        {
            String colors = "";
            
            for(Color c: source.getSelectedPlayer().getColoring())
            {
                colors += c.getRed() + "," + c.getGreen() + "," + c.getBlue() + "-";
            }
            colors = colors.substring(0, colors.length()-1);
            
            return colors;
        }
        else if(request.equals("actvplr_looktype?"))
        {
            return ""+source.getSelectedPlayer().getLookType();
        }
        else if(request.startsWith("actvplr_changecolors:"))
        {
            String colorData = request.split(":")[1];
            Color[] colors = new Color[4];
            {
                //set data
                String[] singleColor = colorData.split("-");

                for(int a = 0; a < singleColor.length; a++)
                {
                    String tehColor = singleColor[a];

                    String[] tehColorData = tehColor.split(",");
                    int r = Integer.parseInt(tehColorData[0]);
                    int g = Integer.parseInt(tehColorData[1]);
                    int b = Integer.parseInt(tehColorData[2]);

                    colors[a] = new Color(r,g,b);
                }
            }
            source.getSelectedPlayer().setColoring(colors);
            return "done";
        }
        else if(request.startsWith("actvplr_setnewlooktype:"))
        {
            String data = request.split(":")[1];
            try
            {
                int newLooktype = Integer.parseInt(data);
                source.getSelectedPlayer().setLookType(newLooktype);
                return "done";
            }
            catch(Exception ex)
            {
                return "";
            }
        }
        else if(request.startsWith("getsessiondata"))
        {            
            GameSession gs = getUsersCurrentSession(source);
            try
            {
                return gs.playerAsksForData(source);
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
                return "";
            }
        }
        else if(request.equals("getactivesessions"))
        {
            String data = "";
            
            for(GameSession gs: activeSessions)
            {
                data += gs.getSessionName()+","+gs.getSessionPlayerCount()+"-";
            }
            
            return data;
        }
        else if(request.equals("getinactivesessions"))
        {
            String data = "";
            
            for(GameSession gs: inactiveSessions)
            {
                data += gs.getSessionName()+","+gs.getSessionPlayerCount()+"-";
            }
            
            return data;
        }
        else if(request.startsWith("connectto:"))
        {
            String session = request.split(":")[1];
            
            GameSession gs = getSession(session);
            
            if(gs == null)
            {
                return "";
            }
            
            gs.playerConnects(source);
            return "done";
        }
        else if(request.equals("becomeDM"))
        {
            GameSession gs = getUsersCurrentSession(source);
            
            if(gs.playerSignsupAsDungeonMaster(source))
            {
                return "done";
            }
            return "";
        }
        else if(request.equals("resignasDM"))
        {
            GameSession gs = getUsersCurrentSession(source);
            
            if(gs.playerSignsoffAsDungeonMaster(source))
            {
                return "done";
            }
            return "";
        }
        else if(request.startsWith("disconnectfrom"))
        {
            GameSession gs = getUsersCurrentSession(source);
            
            gs.playerDisconnects(source);
            
            if(gs.getSessionPlayerCount() == 0)
            {
                if(inactiveSessions.contains(gs))
                {
                    inactiveSessions.remove(gs);
                }
                else if(activeSessions.contains(gs))
                {
                    activeSessions.remove(gs);
                }
            }
            
            return "done";
        }
        else if(request.equals("readyup"))
        {
            GameSession gs = getUsersCurrentSession(source);
            
            gs.playerReadiesUp(source);
            return "done";
        }
        else if(request.equals("cancelreadyup"))
        {
            GameSession gs = getUsersCurrentSession(source);
            
            gs.playerCancelsReadyUp(source);
            return "done";
        }
        else if(request.equals("startsession"))
        {
            GameSession gs = getUsersCurrentSession(source);
            
            boolean success = startGameSession(gs);
            
            if(success)
            {
                logMessageToScreen("Session "+gs.getSessionName()+" has started.");
                return "done";
            }
            return "";
        }
        else if(request.equals("stopsession"))
        {
            GameSession gs = getUsersCurrentSession(source);
            
            //TODO
        }
        else if(request.equals("getsessionlobbydata"))
        {
            GameSession gs = getUsersCurrentSession(source);
            
            return gs.getLobbyData();
        }
        else if(request.startsWith("createsession:"))
        {
            String session = request.split(":")[1];
            
            if(createNewSession(source, session))
            {
                logMessageToScreen("New session \""+session+"\" created by "+source.getUsername());
                return "done";
            }
        }
        else if(request.startsWith("mov"))
        {
            Player p = source.getSelectedPlayer();
            
            char cc = request.charAt(5);
            boolean moving = false;
            if(cc == '1')
            {
                moving = true;
            }
            
            char c = request.charAt(3);
            switch(c)
            {
                case 'N':
                    p.setMovingNorth(moving);
                    break;
                case 'S':
                    p.setMovingSouth(moving);
                    break;
                case 'E':
                    p.setMovingEast(moving);
                    break;
                case 'W':
                    p.setMovingWest(moving);
                    break;
            }
            
        }
        else if(request.startsWith("plrsays"))
        {
            try
            {
                GameSession gs = getUsersCurrentSession(source);
                String encodedtext = request.split(":")[1];
                
                gs.playerSays(source.getSelectedPlayer(), encodedtext);
            }
            catch(Exception ex)
            {
                
            }
        }
        else if(request.startsWith("plrclick"))
        {
            try
            {
                GameSession gs = getUsersCurrentSession(source);
                
                String data = request.split(":")[1];
                gs.playerClicks(source.getSelectedPlayer(), data);
            }
            catch(Exception ex)
            {
                
            }
            //plrclick:"+modClick.x+","+modClick.y
        }
        else if(request.equals("actvplr_eqsummary"))
        {
            try
            {
                Player p = source.getSelectedPlayer();
                
                String data = "";
                          
                Equipment[] equips = {
                    p.getEquippedNecklace(),
                    p.getEquippedHelmet(),
                    p.getEquippedLeftWeapon(),
                    p.getEquippedChestArmor(),
                    p.getEquippedRightWeapon(),
                    p.getEquippedGloves(),
                    p.getEquippedLegArmor(),
                    p.getEquippedBelt(),
                    p.getEquippedLeftRing(),
                    p.getEquippedBoots(),
                    p.getEquippedRightRing()
                };
                
                for(Equipment e: equips)
                {
                    //String name, String type, String description, int id      
                    data += "-";
                    if(e != null)
                    {
                        data += e.getItemName() + "=" + e.getItemType() + "=" + e.getItemAttributes() + "=" + e.getLooktype();
                    }
                    else
                    {
                        data += " ";
                    }
                }
                data = data.substring(1);
                
                return data;
            }
            catch(Exception ex)
            {
                
            }
        }
        else if(request.startsWith("actvplr_inventcontent"))
        {
            try
            {
                String data = "";
                for(Item i: source.getSelectedPlayer().getItems())
                {
                    data += "-";
                    data += i.getItemName() + "=" + i.getItemType() + "=" + i.getItemAttributes() + "=" + i.getLooktype();
                }
                data = data.substring(1);
                
                return data;
            }
            catch(Exception ex)
            {
                
            }
        }
        else if(request.startsWith("plrattemptequip"))
        {
            try
            {
                String indexOfInventoryItemToEquip = request.split(":")[1];
                int idx = Integer.parseInt(indexOfInventoryItemToEquip);
                
                Player p = source.getSelectedPlayer();
                Item i = p.getItems().get(idx);
                
                Equipment itemReplaced = null;
                if(i instanceof Belt)
                {
                    itemReplaced = p.equip((Belt)i);
                    p.getItems().remove(idx);
                }
                else if(i instanceof Boots)
                {
                    itemReplaced = p.equip((Boots)i);
                    p.getItems().remove(idx);
                }
                else if(i instanceof LegArmor)
                {
                    itemReplaced = p.equip((LegArmor)i);
                    p.getItems().remove(idx);
                    //System.out.println(larm.getItemName() + " removed from inventory");
                }
                else if(i instanceof ChestArmor)
                {
                    itemReplaced = p.equip((ChestArmor)i);
                    p.getItems().remove(idx);
                }
                else if(i instanceof Ring)
                {
                    itemReplaced = p.equip((Ring)i);
                    p.getItems().remove(idx);
                }
                else if(i instanceof Helmet)
                {
                    itemReplaced = p.equip((Helmet)i);
                    p.getItems().remove(idx);
                }
                else if(i instanceof Necklace)
                {
                    itemReplaced = p.equip((Necklace)i);
                    p.getItems().remove(idx);
                }
                else if(i instanceof Gloves)
                {
                    itemReplaced = p.equip((Gloves)i);
                    p.getItems().remove(idx);
                }
                
                if(itemReplaced != null)
                {
                    p.addItem(itemReplaced);
                }
                
                if(i instanceof Weapon)
                {
                    Item[] itemReplaced2 = p.equip((Weapon)i);
                    if(itemReplaced2 != null)
                    {
                        for(Item ii: itemReplaced2)
                        {
                            p.addItem(ii);
                        }
                    }
                    p.getItems().remove(idx);
                }
            }
            catch(Exception ex)
            {
                
            }
        }
        else if(request.startsWith("plrunequips"))
        {
            try
            {
                String unequippedItan = request.split(":")[1];
                Player p = source.getSelectedPlayer();
                
                Equipment resultingEQ = null;
                if(unequippedItan.equals("belt"))
                {
                    resultingEQ = p.equip((Belt)null);
                }
                else if(unequippedItan.equals("boots"))
                {
                    resultingEQ = p.equip((Boots)null);
                }
                else if(unequippedItan.equals("chest"))
                {
                    resultingEQ = p.equip((ChestArmor)null);
                }
                else if(unequippedItan.equals("helmet"))
                {
                    resultingEQ = p.equip((Helmet)null);
                }
                else if(unequippedItan.equals("legs"))
                {
                    resultingEQ = p.equip((LegArmor)null);
                }
                else if(unequippedItan.equals("necklace"))
                {
                    resultingEQ = p.equip((Necklace)null);
                }

                if(resultingEQ != null)
                {
                    p.addItem(resultingEQ);
                }
                
                if(unequippedItan.equals("leftring"))
                {
                    Equipment left = p.getEquippedLeftRing();
                    p.addItem(left);
                    p.setEquippedLeftRing(null);
                }
                else if(unequippedItan.equals("rightring"))
                {
                    Equipment right = p.getEquippedRightRing();
                    p.addItem(right);
                    p.setEquippedRightRing(null);
                }
                
                if(unequippedItan.equals("leftweap"))
                {
                    Equipment left = p.getEquippedLeftWeapon();
                    
                    p.addItem(left);
                    p.setEquippedLeftWeapon(null);
                }
                else if(unequippedItan.equals("rightweap"))
                {
                    Equipment right = p.getEquippedRightWeapon();
                    
                    p.addItem(right);
                    p.setEquippedRightWeapon(null);
                }
            }
            catch(Exception ex)
            {
                
            }
        }
        return "";
    }
    
    public GameSession getUsersCurrentSession(User u)
    {
        GameSession gs = null;
        for(GameSession gss: activeSessions)
        {
            if(gss.getIndexOfPlayer(u) != -1)
            {
                gs = gss;
            }
        }
        for(GameSession gss: inactiveSessions)
        {
            if(gss.getIndexOfPlayer(u) != -1)
            {
                gs = gss;
            }
        }

        return gs;
    }
    public GameSession getSession(String session)
    {
        GameSession gs = null;
        for(GameSession gss: activeSessions)
        {
            if(gss.getSessionName().toLowerCase().equals(session.toLowerCase()))
            {
                gs = gss;
            }
        }
        for(GameSession gss: inactiveSessions)
        {
            if(gss.getSessionName().toLowerCase().equals(session.toLowerCase()))
            {
                gs = gss;
            }
        }

        return gs;
    }
    
    public boolean createNewSession(User starter, String sessionName)
    {
        for(GameSession gs: activeSessions)
        {
            if(gs.getSessionName().toLowerCase().equals(sessionName.toLowerCase()))
            {
                return false;
            }
        }
        for(GameSession gs: inactiveSessions)
        {
            if(gs.getSessionName().toLowerCase().equals(sessionName.toLowerCase()))
            {
                return false;
            }
        }
        
        GameSession gs = new GameSession(this, sessionName);
        //gs.playerConnects(starter);
        inactiveSessions.add(gs);
        
        return true;
    }
    
    public boolean startGameSession(String sessionName)
    {
        for(GameSession gs: inactiveSessions)
        {
            if(gs.getSessionName().toLowerCase().equals(sessionName.toLowerCase()))
            {
                return startGameSession(gs);
            }
        }
        return false;
    }
    public boolean startGameSession(GameSession gs)
    {
        if(gs.isSessionReadyToStart())
        {
            Thread t = new Thread(gs);
            t.start();
            activeSessionThreads.add(t);

            activeSessions.add(gs);
            inactiveSessions.remove(gs);
            
            
            //TODO ?
            
            return true;
        }
        return false;
    }
    public void endGameSession(String sessionName)
    {
        for(GameSession gs: inactiveSessions)
        {
            if(gs.getSessionName().toLowerCase().equals(sessionName.toLowerCase()))
            {
                endGameSession(gs);
            }
        }
    }
    public void endGameSession(GameSession gs)
    {
        //TODO ?
        
        
    }
}
